package com.cxs.videoplayer.provider;

import com.cxs.videoplayer.ResourceTable;
import com.cxs.videoplayer.data.VideoInfo;
import com.cxs.videoplayer.util.VideoUtils;
import ohos.agp.components.*;

import java.util.List;

public class VideoListProvider extends BaseItemProvider {

    private List<VideoInfo> videoInfos;
    private ItemClickedListener itemClickedListener;

    public VideoListProvider(List<VideoInfo> videoInfos) {
        this.videoInfos = videoInfos;
    }

    public void setVideoClickedListener(ItemClickedListener itemClickedListener) {
        this.itemClickedListener = itemClickedListener;
    }

    @Override
    public int getCount() {
        return videoInfos.size();
    }

    @Override
    public Object getItem(int i) {
        if (videoInfos != null && i < videoInfos.size()) {
            return videoInfos.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        ViewHolder viewHolder;
        if (component == null) {
            cpt = LayoutScatter.getInstance(componentContainer.getContext())
                    .parse(ResourceTable.Layout_video_list_item, null, false);
            viewHolder = new ViewHolder(cpt);
            cpt.setTag(viewHolder);
        } else {
            cpt = component;
            viewHolder = (ViewHolder)cpt.getTag();
        }
        VideoInfo videoInfo = videoInfos.get(i);
        if (viewHolder != null) {
            viewHolder.thumbnail.setPixelMap(VideoUtils.getPixelMap(videoInfo.getThumbnail()));
            viewHolder.title.setText(videoInfo.getTitle());
            viewHolder.synopsis.setText(videoInfo.getSynopsis());
        }
        // 点击视频的回调
        if (videoInfo != null) {
            cpt.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    itemClickedListener.onClicked(videoInfo);
                }
            });
        }
        return cpt;
    }

    private static class ViewHolder {
        Image thumbnail;
        Text title;
        Text synopsis;

        public ViewHolder(Component component) {
            thumbnail = (Image)component.findComponentById(ResourceTable.Id_video_thumbnail);
            title = (Text)component.findComponentById(ResourceTable.Id_video_title);
            synopsis = (Text)component.findComponentById(ResourceTable.Id_video_synopsis);
        }
    }

    public interface ItemClickedListener {
        void onClicked(VideoInfo videoInfo);
    }
}
